package cloud.xuxiaowei.core.filter;

import cloud.xuxiaowei.utils.RequestUtils;
import cloud.xuxiaowei.utils.servlet.InputStreamHttpServletRequestWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求流转换为多次读取的请求流 过滤器
 * <p>
 * 使用配置文件进行条件注解为 {@link Bean}，并将优先级调高或指定请求地址单独配置
 * <p>
 * 此处将优先级调高，也可根据请求地址单独配置
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
@Setter
@Component
public class HttpServletRequestInputStreamFilter extends HttpFilter implements Ordered {

	public static final int ORDERED = Ordered.HIGHEST_PRECEDENCE + 10000;

	private int order = ORDERED;

	@Override
	public int getOrder() {
		return this.order;
	}

	@Override
	protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		String contentType = request.getContentType();
		// 仅记录 JSON 响应
		if (MediaType.APPLICATION_JSON_VALUE.equals(contentType)) {
			// 将请求流转换为可多次读取的请求流
			HttpServletRequest requestWrapper = new InputStreamHttpServletRequestWrapper(request);

			String requestBody = RequestUtils.getInputStream(requestWrapper);

			log.info("HttpServletRequest Body: {}", requestBody);

			chain.doFilter(requestWrapper, response);
			return;
		}

		chain.doFilter(request, response);
	}

}
